package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.to.mq.TaskDetailEntityTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.exception.NoStockException;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareOrderTaskService orderTaskService;
    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {


        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId= (String) params.get("skuId");
        String wareId= (String) params.get("wareId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(new Query<WareSkuEntity>().getPage(params), wrapper);


        return new PageUtils(page);
    }

    @Override
    public void updateNum(Long skuId, Long wareId, Integer skuNum) {
        List<WareSkuEntity> list = this.list(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (list==null ||list.size()==0){
            //新增仓库信息
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            this.save(wareSkuEntity);
        }else {
            //改变库存数量
            baseMapper.updateNum(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStockVoBySkuIds(List<Long> skuIds) {
        List<SkuHasStockVo> skuHasStockVos = skuIds.stream().map(skuid -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            Long count=baseMapper.hasStockBySkuId(skuid);
            skuHasStockVo.setHasStock(count==null?false:count>0);
            skuHasStockVo.setSkuId(skuid);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return skuHasStockVos;
    }

    @Transactional
    @Override
    public Boolean lock(WareSkuLockVo wareSkuLockVo) {
        //创建一个	`wms_ware_order_task`
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        orderTaskService.save(wareOrderTaskEntity);
        Long taskEntityId = wareOrderTaskEntity.getId();

        List<OrderItemVo> locks = wareSkuLockVo.getLocks();
        List<SkuWareHasStock> skuWareHasStocks = locks.stream().map(item -> {
            //查询商品在哪个仓库有库存
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(item.getSkuId());
            skuWareHasStock.setNum(item.getCount());
            List<Long> wareIds=baseMapper.listWareIdsHasStock(item.getSkuId());
            skuWareHasStock.setWareIds(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());

//        锁定库存 循环每一个商品 锁定库存
        for (SkuWareHasStock skuWareHasStock : skuWareHasStocks) {
            Boolean skuStock=false;
            Long skuId = skuWareHasStock.getSkuId();
            List<Long> wareIds = skuWareHasStock.getWareIds();
            Integer num = skuWareHasStock.getNum();
            if (wareIds==null || wareIds.size()==0){
                throw new NoStockException(skuId);
            }
            /**
             * 每一个商品都锁定成功了，数据库生成taskdetail记录，向mq发送一个消息 告诉mq 锁定库存的详细信息taskdetail
             * 如果锁定失败了 直接回滚不锁定库存，不会生成taskdetail记录，就算向mq发送了消息，mq做检查的时候发现数据库里没有对应的taskdetail，也不会做解锁库存操作
             */
            for (Long wareId : wareIds) {
                //锁定库存
                int count = baseMapper.lockStock(skuId, wareId, num);
                if (count==0){
                    //库存不足，锁定失败 判断下一个仓库
                }else if (count==1){
//                锁定库存成功，创建一个ware_order_task_detail`
                    WareOrderTaskDetailEntity orderTaskDetailEntity = new WareOrderTaskDetailEntity();
                    orderTaskDetailEntity.setSkuId(skuId);
                    orderTaskDetailEntity.setWareId(wareId);
                    orderTaskDetailEntity.setTaskId(taskEntityId);
                    orderTaskDetailEntity.setSkuName("");
                    orderTaskDetailEntity.setSkuNum(num);
                    orderTaskDetailEntity.setLockStatus(1);
                    orderTaskDetailService.save(orderTaskDetailEntity);
                    //锁定成功 向mq发送延迟消息
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setTaskId(taskEntityId);
                    TaskDetailEntityTo taskDetailEntityTo = new TaskDetailEntityTo();
                    BeanUtils.copyProperties(orderTaskDetailEntity,taskDetailEntityTo);
                    stockLockedTo.setDetailEntityTo(taskDetailEntityTo);
//                    String exchange, String routingKey, Object message
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                    //锁定库存成功，换下一个商品
                    skuStock=true;
                    break;
                }
            }
            if (skuStock==false){
                throw new NoStockException(skuId);
            }
        }

        return true;
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private List<Long> wareIds;
        private Integer num;
    }

}